<template>
  <div class="table-container">
    <vab-query-form>
      <vab-query-form-left-panel>
        <el-form ref="form" :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="queryForm.title" placeholder="请输入账单名称" />
          </el-form-item>
          <el-form-item>
            <el-select v-model="queryForm.status" clearable placeholder="账单状态">
              <el-option label="全部" value="" />
              <el-option label="待支付" value="draft" />
              <el-option label="已支付" value="published" />
              <el-option label="已取消" value="deleted" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" native-type="submit" type="primary" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
    </vab-query-form>

    <el-table
      ref="tableSort"
      v-loading="listLoading"
      :data="list"
      :element-loading-text="elementLoadingText"
      :height="height"
      @selection-change="setSelectRows"
      @sort-change="tableSortChange"
    >
      <el-table-column show-overflow-tooltip type="selection" width="55" />
      <el-table-column label="订单号" show-overflow-tooltip width="180">
        <template #default="scope">
          {{ scope.row.orderNo || `订单${scope.$index + 1}` }}
        </template>
      </el-table-column>
      <el-table-column label="账单名称" prop="title" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.productName || scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="供货商" prop="author" show-overflow-tooltip>
        <template #default="scope">
          {{ scope.row.supplierLabel || scope.row.author }}
        </template>
      </el-table-column>
      <el-table-column label="价格" prop="pageViews" show-overflow-tooltip sortable>
        <template #default="scope">
          {{ calculatePrice(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="账单状态" show-overflow-tooltip>
        <template #default="{ row }">
          <el-tooltip class="item" :content="row.billStatus || '待支付'" effect="dark" placement="top-start">
            <el-tag :type="(row.billStatus || '待支付') | statusFilter">
              {{ row.billStatus || '待支付' }}
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="时间" prop="datetime" show-overflow-tooltip width="200">
        <template #default="scope">
          {{ scope.row.createTime || scope.row.datetime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" show-overflow-tooltip width="180px">
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
          <el-button v-if="row.billStatus === '待支付' || !row.billStatus" type="text" @click="handlePay(row)">去支付</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :background="background"
      :current-page="queryForm.pageNo"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <table-edit ref="edit" />

    <!-- 支付确认弹窗 -->
    <el-dialog title="支付确认" :visible.sync="payDialogVisible" width="500px">
      <div class="pay-info">
        <p><strong>订单号：</strong>{{ currentPayOrder.orderNo }}</p>
        <p><strong>商品名称：</strong>{{ currentPayOrder.productName || currentPayOrder.title }}</p>
        <p><strong>供应商：</strong>{{ currentPayOrder.supplierLabel || currentPayOrder.author }}</p>
        <p><strong>支付金额：</strong>¥ {{ calculatePrice(currentPayOrder) }}</p>
      </div>
      <div class="pay-method">
        <p><strong>支付方式：</strong></p>
        <el-radio-group v-model="payMethod">
          <el-radio label="alipay">支付宝</el-radio>
          <el-radio label="wechat">微信支付</el-radio>
          <el-radio label="bank">银行转账</el-radio>
        </el-radio-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPay">确认支付</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { doDelete, getList } from '@/api/table'
  import TableEdit from './components/TableEdit'

  export default {
    name: 'ComprehensiveTable',
    components: {
      TableEdit,
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '待支付': 'warning',
          '已完成': 'success',
          '已取消': 'danger'
        }
        return statusMap[status] || 'info'
      },
      // 状态文本映射
      statusTextFilter(status) {
        return status || '未知状态'
      },
    },
        beforeRouteEnter(to, from, next) {
      next(vm => {
        // 如果是从支付页面返回，并且有支付成功的参数
        if (from.path === '/mall/pay' && to.query.paySuccess) {
          // 获取支付信息
          const paymentInfo = localStorage.getItem('currentPaymentInfo')
          if (paymentInfo) {
            const payment = JSON.parse(paymentInfo)

            // 更新支付历史记录
            const paymentHistory = JSON.parse(localStorage.getItem('paymentHistory') || '[]')
            paymentHistory.push({
              ...payment,
              paymentTime: new Date().toLocaleString()
            })
            localStorage.setItem('paymentHistory', JSON.stringify(paymentHistory))

            // 刷新数据
            vm.loadPurchaseOrders()
            vm.fetchData()

            // 显示支付成功提示
            vm.$baseMessage('支付成功', 'success')
          }
        }
      })
    },
    data() {
      return {
        imgShow: true,
        list: [],
        imageList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        selectRows: '',
        elementLoadingText: '正在加载...',
        queryForm: {
          pageNo: 1,
          pageSize: 20,
          title: '',
          status: '',
        },
        timeOutID: null,
        // 支付相关
        payDialogVisible: false,
        currentPayOrder: {},
        payMethod: 'alipay',
        // 订单数据
        purchaseOrders: [],
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    created() {
      this.loadPurchaseOrders()
      this.fetchData()
    },
    beforeDestroy() {
      clearTimeout(this.timeOutID)
    },
    mounted() {},
    methods: {
      // 加载采购订单数据
      loadPurchaseOrders() {
        const storedData = localStorage.getItem('purchaseTableData')
        if (storedData) {
          try {
            const originalOrders = JSON.parse(storedData)
            // 将采购订单转换为账单格式，使用新的状态字段
            this.purchaseOrders = originalOrders.map(order => {
              // 检查是否已经支付过
              const paymentHistory = JSON.parse(localStorage.getItem('paymentHistory') || '[]')
              const isPaid = paymentHistory.some(payment => payment.orderNo === order.orderNo)

              return {
                ...order,
                // 使用简单的状态：待支付、已完成
                billStatus: isPaid ? '已完成' : '待支付',
                // 设置价格（这里使用数量作为基础计算）
                pageViews: order.quantity * (Math.floor(Math.random() * 500) + 100),
              }
            })

            // 统计待支付订单数量并存储到localStorage
            this.updatePendingOrdersCount();
          } catch (error) {
            console.error('解析采购订单数据失败:', error)
          }
        }
      },

      // 新增：统计待支付订单数量并存储到localStorage
      updatePendingOrdersCount() {
        try {
          // 统计待支付订单数量
          const pendingOrders = this.purchaseOrders.filter(order =>
            order.billStatus === '待支付' || !order.billStatus
          ).length;

          // 存储到localStorage
          localStorage.setItem('pendingOrdersCount', pendingOrders.toString());
          console.log('待支付订单数量已更新:', pendingOrders);
        } catch (error) {
          console.error('更新待支付订单数量失败:', error);
        }
      },

      // 计算价格
      calculatePrice(row) {
        if (row.pageViews) {
          return `¥ ${row.pageViews}`
        } else if (row.quantity) {
          // 如果没有价格但有数量，生成一个随机价格
          const price = row.quantity * (Math.floor(Math.random() * 500) + 100)
          return `¥ ${price}`
        }
        return '¥ 0'
      },
      tableSortChange() {
        const imageList = []
        this.$refs.tableSort.tableData.forEach((item, index) => {
          imageList.push(item.img)
        })
        this.imageList = imageList
      },
      setSelectRows(val) {
        this.selectRows = val
      },
      handleAdd() {
        this.$refs['edit'].showEdit()
      },
      handleEdit(row) {
        this.$refs['edit'].showEdit(row)
      },
      // 处理支付
      handlePay(row) {
        this.currentPayOrder = row
        this.payDialogVisible = true
      },
      // 确认支付
      confirmPay() {
        // 准备支付信息
        const paymentInfo = {
          orderNo: this.currentPayOrder.orderNo || `订单${Date.now()}`,
          productName: this.currentPayOrder.productName || this.currentPayOrder.title,
          supplierName: this.currentPayOrder.supplierLabel || this.currentPayOrder.author,
          quantity: this.currentPayOrder.quantity || 1,
          warehouseLabel: this.currentPayOrder.warehouseLabel || '默认仓库',
          price: this.calculatePrice(this.currentPayOrder),
          payMethod: this.payMethod,
          paymentTime: new Date().toLocaleString()
        }

        // 存储当前支付信息到localStorage
        localStorage.setItem('currentPaymentInfo', JSON.stringify(paymentInfo))

        // 直接更新支付历史记录
        const paymentHistory = JSON.parse(localStorage.getItem('paymentHistory') || '[]')
        paymentHistory.push({
          ...paymentInfo,
          paymentTime: new Date().toLocaleString()
        })
        localStorage.setItem('paymentHistory', JSON.stringify(paymentHistory))

        // 更新当前订单状态
        if (this.currentPayOrder.orderNo) {
          // 更新purchaseTableData中的订单状态
          const purchaseData = JSON.parse(localStorage.getItem('purchaseTableData') || '[]')
          const orderIndex = purchaseData.findIndex(order => order.orderNo === this.currentPayOrder.orderNo)
          if (orderIndex !== -1) {
            purchaseData[orderIndex].billStatus = '已完成'
            localStorage.setItem('purchaseTableData', JSON.stringify(purchaseData))
          }

          // 更新当前列表中的订单状态
          const listIndex = this.list.findIndex(item => item.orderNo === this.currentPayOrder.orderNo)
          if (listIndex !== -1) {
            this.list[listIndex].billStatus = '已完成'
          }
        }

        // 支付完成后更新待支付订单数量
        this.updatePendingOrdersCount();

        // 关闭支付弹窗
        this.payDialogVisible = false

        // 显示支付成功提示
        // this.$baseMessage('支付成功', 'success')

        // 跳转到支付页面
        this.$router.push('/vab/pay')
      },
      handleDelete(row) {
        if (row.id) {
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await doDelete({ ids: row.id })
            this.$baseMessage(msg, 'success')
            this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => item.id).join()
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await doDelete({ ids: ids })
              this.$baseMessage(msg, 'success')
              this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error')
            return false
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      handleQuery() {
        this.queryForm.pageNo = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true

        try {
          // 从localStorage获取订单数据
          const purchaseData = JSON.parse(localStorage.getItem('purchaseTableData') || '[]')

          // 过滤订单数据
          let filteredOrders = [...purchaseData]

          // 根据查询条件过滤
          if (this.queryForm.title) {
            filteredOrders = filteredOrders.filter(order =>
              (order.productName && order.productName.includes(this.queryForm.title)) ||
              (order.orderNo && order.orderNo.includes(this.queryForm.title))
            )
          }

          if (this.queryForm.status) {
            filteredOrders = filteredOrders.filter(order => order.status === this.queryForm.status)
          }

          // 分页处理
          const startIndex = (this.queryForm.pageNo - 1) * this.queryForm.pageSize
          const endIndex = startIndex + this.queryForm.pageSize

          // 截取当前页数据
          this.list = filteredOrders.slice(startIndex, endIndex)

          // 计算总数
          this.total = filteredOrders.length

          // 处理图片列表
          const imageList = []
          this.list.forEach((item) => {
            if (item.img) imageList.push(item.img)
          })
          this.imageList = imageList

          // 更新待支付订单数量
          this.updatePendingOrdersCount();
        } catch (error) {
          console.error('获取数据失败:', error)
          this.list = []
          this.total = 0
        }

        this.timeOutID = setTimeout(() => {
          this.listLoading = false
        }, 500)
      },
      testMessage() {
        this.$baseMessage('test1', 'success')
      },
      testALert() {
        this.$baseAlert('11')
        this.$baseAlert('11', '自定义标题', () => {
          /* 可以写回调; */
        })
        this.$baseAlert('11', null, () => {
          /* 可以写回调; */
        })
      },
      testConfirm() {
        this.$baseConfirm(
          '你确定要执行该操作?',
          null,
          () => {
            /* 可以写回调; */
          },
          () => {
            /* 可以写回调; */
          }
        )
      },
      testNotify() {
        this.$baseNotify('测试消息提示', 'test', 'success', 'bottom-right')
      },
    },
  }
</script>

<style scoped>
.pay-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.pay-info p {
  margin: 8px 0;
}

.pay-method {
  margin-top: 20px;
}
</style>
